<template>
   <div>
      <!-- 搜索框 -->
      <a-row :gutter="10" class="toolbar">
         <a-col :span="6">
            <a-input-search placeholder="按员工姓名查找" v-model="staffName" enterButton @search="onSearch"></a-input-search>
         </a-col>
         <a-col :span="3">
            <a-button type="primary" @click="exportCsv">导出员工列表</a-button>
         </a-col>
         <a-col :span="3">
            <a-button type="primary" @click="inviteStaff">邀请新员工</a-button>
         </a-col>
         <a-col :span="3">
            <a-button type="primary" @click="batchInviteStaff">批量邀请新员工</a-button>
         </a-col>
         <a-col :offset="2" :span="4">
            <custom-icon type="icon-down"></custom-icon>
            <a class="downloadTemplate" @click="handleDownloadTemplate">下载批量邀请模板</a>
         </a-col>
      </a-row>
      <div>
         <a-table
            :columns="columns"
            :dataSource="formData"
            :loading="loading"
            :pagination="pagination"
            @change="onPaginationChange"
            rowKey="id"
         >
				<span slot="action" slot-scope="text, record, index">
					<a href="javascript:;" @click="() => viewDetail(text, record, index)">设置</a>
				</span>
            <span slot="switch" slot-scope="text, record, index">
					<a-switch
                  checkedChildren="开"
                  unCheckedChildren="关"
                  @change="switchState(record, index)"
                  :checked="text.toLowerCase()==='active'"
               />
				</span>
         </a-table>
      </div>
      <div>
         <a-modal
            title="员工设置"
            :visible="detailVisible"
            @cancel="handleCancel"
            @ok="handleOk"
            :width="660"
            :maskClosable="false"
         >
            <div>
               <a-row>
                  <a-col :span="12">姓名：{{record.name}}</a-col>
                  <a-col :span="12">当前已用额度：{{record.amountUsed}}</a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12">
                     个人额度：
                     <a-input-number
                        :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                        :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                        v-model="settings.newAmount"
                        style="width: 50%"
                     />
                  </a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12">
                     单日转账限额：
                     <a-input-number
                        :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                        :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                        v-model="settings.dayLimit"
                        style="width: 50%"
                     />
                  </a-col>
               </a-row>
               <a-row style="margin-top: 15px">
                  <a-col :span="12">
                     单月转账限额：
                     <a-input-number
                        :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                        :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                        v-model="settings.monthLimit"
                        style="width: 50%"
                     />
                  </a-col>
               </a-row>
            </div>
         </a-modal>
      </div>
   </div>
</template>
<script>
import { get, post } from '@/utils/http'
import { formatMoney } from '@/utils/util'
import { getCookie } from '@/utils/cookieUtils'
import customIcon from '@/utils/customIcon'

const columns = [
   {
      title: '姓名',
      dataIndex: 'name'
   },
   {
      title: '授信额度',
      dataIndex: 'amountTotal',
      customRender: text => {
         return formatMoney(text)
      }
   },
   {
      title: '福利卡额度',
      dataIndex: 'welfareTotalAmount',
      customRender: text => {
         return formatMoney(text)
      }
   },
   {
      title: '已用额度',
      dataIndex: 'amountUsed',
      customRender: text => {
         return formatMoney(text)
      }
   },
   {
      title: '状态',
      dataIndex: 'state',
      customRender: text => {
         switch (text.toLowerCase()) {
            case 'pending':
               return '待激活'
            case 'waiting':
               return '未绑卡'
            case 'normal':
               return '已绑卡'
            case 'deactivate':
               return '已禁用'
         }
      }
   },
   {
      title: '账户',
      dataIndex: 'accountState',
      scopedSlots: { customRender: 'switch' }
   },
   {
      title: '操作',
      key: 'action',
      scopedSlots: { customRender: 'action' }
   }
]

export default {
   data () {
      return {
         detailVisible: false,
         staffName: '',
         formData: [],
         loading: false,
         record: {},
         index: '',
         settings: {
            newAmount: 0,
            dayLimit: 0,
            monthLimit: 0
         },
         columns,
         pagination: {
            showSizeChanger: true,
            showQuickJumper: true,
            position: 'bottom',
            pageNum: 1,
            pageSize: 10
         }
      }
   },
   components: {
      customIcon
   },
   created () {
      this.fetchStaffListByEntId()
   },
   methods: {
      fetchStaffListByEntId () {
         this.loading = true

         let url = `/staff/listByEntIdAndStaffName`
         get(url, {
            entId: getCookie('entId'),
            staffName: this.staffName,
            pageNum: this.pagination.pageNum,
            pageSize: this.pagination.pageSize
         }).then(res => {
            this.$message.success('查询成功')
            let pagination = { ...this.pagination }
            pagination.total = res.total
            this.pagination = pagination
            this.formData = res.list
         }).catch(err => {
            this.$message.error(err)
         }).finally(() => {
            this.loading = false
         })
      },
      // 按照员工姓名查找
      onSearch () {
         this.resetPaginationSetting()
         this.fetchStaffListByEntId()
      },

      resetPaginationSetting () {
         this.$set(this, 'pagination', {
            pageNum: 1,
            pageSize: 10,
            total: 0
         })
      },
      // 监听表格变化（这里只关注分页变化）
      onPaginationChange (pagination) {
         this.pagination.pageNum = pagination.current
         this.pagination.pageSize = pagination.pageSize
         this.fetchStaffListByEntId()
      },
      // 导出员工列表
      exportCsv () {
         get('/staff/csv/export_acct', {
            entId: getCookie('entId'),
            entName: getCookie('entName'),
            staffName: this.staffName
         }).then(res => {
            this.filePath = res.fileUrl
            this.fileName = res.fileName

            fetch(this.filePath).then(res => {
                  res.blob().then(blob => {
                     if ('msSaveOrOpenBlob' in navigator) {
                        // Microsoft Edge and Microsoft Internet Explorer 10-11
                        window.navigator.msSaveOrOpenBlob(blob, self.fileName)
                     } else {
                        let a = document.createElement('a')
                        let url = window.URL.createObjectURL(blob)
                        a.href = url
                        a.download = this.fileName
                        a.click()
                        URL.revokeObjectURL(url)
                     }
                  })
               }
            )
         })
      },
      handleCancel (e) {
         this.detailVisible = false
      },
      handleOk (e) {
         let self = this
         let url = '/staff/changeStaffConfig/' + self.record.id

         post(url, self.settings)
            .then(() => {
               self.$message.success('修改成功', 3)
               const data = [...self.formData]
               data[self.index].amountTotal = self.settings.newAmount
               data[self.index].dayLimit = self.settings.dayLimit
               data[self.index].monthLimit = self.settings.monthLimit
               self.formData = data

               self.settings = {}
               self.index = ''
               self.detailVisible = false
            })
            .catch(err => {
               self.$message.error(err.msg, 3)
            })
      },
      switchState (record, index) {
         let self = this
         let url = ''
         if (record.accountState === 'ACTIVE') {
            url = '/staff/disable/' + record.id
            get(url, {})
               .then(res => {
                  self.$message.success('支付功能已关闭', 3)
                  const data = [...self.formData]
                  data[index].accountState = 'DISABLE'
                  self.formData = data
               })
               .catch(err => {
                  self.$message.error(err.msg, 3)
               })
         } else {
            url = '/staff/active/' + record.id
            get(url, {})
               .then(res => {
                  self.$message.success('支付功能已打开', 3)
                  const data = [...self.formData]
                  data[index].accountState = 'ACTIVE'
                  self.formData = data
               })
               .catch(err => {
                  self.$message.error(err.msg, 3)
               })
         }
      },
      viewDetail (text, record, index) {
         this.record = record
         this.settings.newAmount = record.amountTotal
         this.settings.dayLimit = record.dayLimit
         this.settings.monthLimit = record.monthLimit
         this.index = index
         this.detailVisible = true
      },
      // 下载批量Excel模板
      handleDownloadTemplate (e) {
         e.preventDefault()
      },
      // 邀请员工
      inviteStaff () {

      },
      // 批量邀请
      batchInviteStaff () {

      }
   }
}
</script>
<style lang="less" scoped>
.toolbar {
   height: 60px;
   line-height: 60px;

   .ant-btn {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 12px;
   }

   .downloadTemplate {
      font-size: 12px;
      text-decoration: underline;
   }
}
</style>
